<template>
  <view class="c-counter">
    <view class="counter-btn" @tap="onRemove"><c-icon icon="remove" :color="removeDisable ? '#C4C4C4' : null" size="40"></c-icon></view>
    <view class="counter-input"><input :disabled="props.disabled" type="number" v-model="thisValue" @blur="onBlur" /></view>
    <view class="counter-btn" @tap="onAdd"><c-icon icon="add" :color="addDisable ? '#C4C4C4' : null" size="40"></c-icon></view>
  </view>
</template>
<script setup>
import { View, Input } from '@tarojs/components';
import { computed, ref, watch } from 'vue';
import { CIcon } from '.';
const props = defineProps({
  min: Number,
  max: Number,
  disabled: Boolean,
  modelValue: Number
});

const emit = defineEmits(['update:modelValue', 'change']);
const thisValue = ref(props.modelValue);

const removeDisable = computed(() => {
  if (props.disabled) return true;
  return props.min == null ? false : props.modelValue <= props.min;
});

const addDisable = computed(() => {
  if (props.disabled) return true;
  return props.max == null ? false : props.modelValue >= props.max;
});

const onRemove = () => {
  if (removeDisable.value) return;
  const newValue = props.modelValue - 1;
  thisValue.value = newValue;
  emit('update:modelValue', newValue);
  emit('change', newValue);
};
const onAdd = () => {
  if (addDisable.value) return;
  const newValue = props.modelValue + 1;
  thisValue.value = newValue;
  emit('update:modelValue', newValue);
  emit('change', newValue);
};
const onBlur = () => {
  if (props.max != null && thisValue.value > props.max) {
    thisValue.value = props.max;
  }
  if (props.min != null && thisValue.value < props.min) {
    thisValue.value = props.min;
  }
  emit('update:modelValue', thisValue.value);
  emit('change', thisValue.value);
};
watch(
  () => props.modelValue,
  () => {
    if (props.modelValue != thisValue.value) {
      thisValue.value = props.modelValue;
    }
  }
);
</script>
<style lang="scss">
.c-counter {
  display: flex;
  .counter-btn {
    height: 52px;
    width: 52px;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: var(--color-background);
    border-radius: 10px;
  }
  .counter-input {
    width: 106px;
    padding: 0 8px;
    input {
      line-height: 52px;
      height: 52px;
      text-align: center;
    }
  }
}
</style>
